<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('编辑实验评分标准')" />
    <style>
        .item-panel {
            border: 1px solid #e5e6e7;
            border-radius: 4px;
            padding: 15px;
            margin-bottom: 15px;
        }
        .item-header {
            margin-bottom: 10px;
            padding-bottom: 10px;
            border-bottom: 1px dashed #e5e6e7;
        }
        .level-item {
            margin-bottom: 10px;
            padding: 10px;
            background-color: #f9f9f9;
            border-radius: 4px;
        }
        .btn-remove {
            color: #f0ad4e;
            cursor: pointer;
        }
        .btn-remove:hover {
            color: #d9534f;
        }
        .form-group.has-error .form-control {
            border-color: #ed5565;
        }
        .error-message {
            color: #ed5565;
            font-size: 12px;
            margin-top: 5px;
            display: none;
        }
        .form-group.has-error .error-message {
            display: block;
        }
    </style>
</head>
<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-sm-12">
            <div class="ibox float-e-margins">
                <div class="ibox-title">
                    <h5>编辑实验评分标准 <small th:text="${course?.courseName ?: '未选择课程'}">课程名称</small></h5>
                    <div class="ibox-tools">
                        <a class="collapse-link">
                            <i class="fa fa-chevron-up"></i>
                        </a>
                    </div>
                </div>
                <div class="ibox-content">
                    <form class="form-horizontal m" id="form-score-standard">
                        <input type="hidden" name="standardId" th:value="${scoreStandard?.standardId}" />
                        <input type="hidden" name="courseId" th:value="${scoreStandard?.courseId}" />
                        <input type="hidden" name="courseName" th:value="${scoreStandard?.courseName}" />
                        <input type="hidden" name="arrangementId" th:value="${scoreStandard?.arrangementId}" />

                        <div class="form-group">
                            <label class="col-sm-2 control-label is-required">评分标准名称：</label>
                            <div class="col-sm-10">
                                <input type="text" name="standardName"
                                       th:value="${scoreStandard?.standardName}"
                                       class="form-control" required placeholder="请输入评分标准名称">
                                <div class="error-message">请输入评分标准名称</div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-2 control-label is-required">总分值：</label>
                            <div class="col-sm-10">
                                <input type="number" name="totalScore"
                                       th:value="${scoreStandard?.totalScore ?: 100}"
                                       class="form-control" required min="1" placeholder="请输入总分值">
                                <div class="error-message">总分值必须大于0</div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-2 control-label is-required">评分项：</label>
                            <div class="col-sm-10">
                                <div id="scoreItemsContainer">
                                    <!-- 评分项将通过JavaScript动态加载或添加 -->
                                </div>
                                <div class="text-center">
                                    <button type="button" class="btn btn-sm btn-primary" id="addItemBtn">
                                        <i class="fa fa-plus"></i> 添加评分项
                                    </button>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-2 control-label">备注：</label>
                            <div class="col-sm-10">
                                    <textarea name="remark" class="form-control" rows="3"
                                              th:text="${scoreStandard?.remark}" placeholder="请输入备注信息"></textarea>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-sm-4 col-sm-offset-2">
                                <button type="button" class="btn btn-primary" id="submitBtn">保存</button>
<!--                                <button type="button" class="btn btn-white" onclick="history.back()">返回</button>-->
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<th:block th:include="include :: footer" />
<script>
    // 改进的serializeObject方法，支持数组嵌套对象格式（如scoreItems[0].itemName）
    $.fn.serializeObject = function() {
        var obj = {};
        var arr = this.serializeArray();

        $.each(arr, function() {
            // 处理数组格式的字段名，如"scoreItems[0].itemName"
            var name = this.name;
            var value = this.value || '';

            // 拆分字段名（支持数组索引和嵌套属性）
            var keys = name.match(/[^\[\].]+/g);
            if (!keys) return;

            var current = obj;
            // 遍历字段名片段，构建嵌套对象/数组
            for (var i = 0; i < keys.length; i++) {
                var key = keys[i];
                // 最后一个片段直接赋值
                if (i === keys.length - 1) {
                    // 处理数字类型
                    if (!isNaN(value) && value !== '') {
                        current[key] = Number(value);
                    } else {
                        current[key] = value;
                    }
                } else {
                    // 非最后一个片段，需要判断是否为数组或对象
                    var nextKey = keys[i + 1];
                    // 如果下一个键是数字，当前应该是数组
                    if (!isNaN(parseInt(nextKey)) && current[key] === undefined) {
                        current[key] = [];
                    }
                    // 如果当前键不存在，初始化为对象
                    if (current[key] === undefined) {
                        current[key] = {};
                    }
                    // 进入下一级
                    current = current[key];
                }
            }
        });
        return obj;
    };
</script>
<script th:inline="javascript">
    var prefix = ctx + "college/scoreStandard";
    // 从后端获取的评分标准数据，增加空值处理
    var scoreStandard = [[${scoreStandard != null ? scoreStandard : {}}]];
    // 初始化评分项索引，确保从已有评分项数量开始
    var itemIndex = scoreStandard.scoreItems && scoreStandard.scoreItems.length ? scoreStandard.scoreItems.length : 0;

    // 生成评分项HTML，增强空值处理
    function generateItemHtml(item, index) {
        // 确保item是对象，避免null引用错误
        item = item || {itemName: '', itemWeight: 0, scoreLevels: []};
        var itemId = "item_" + index;
        var html = '<div class="item-panel" id="' + itemId + '">';
        html += '<div class="item-header">';
        html += '<div class="form-group">';
        html += '<label class="col-sm-2 control-label">评分项 ' + (index + 1) + '：</label>';
        html += '<div class="col-sm-6">';
        html += '<input type="text" name="scoreItems[' + index + '].itemName" ' +
            'value="' + (item.itemName || '') + '" class="form-control" placeholder="请输入评分项名称" required>';
        html += '<div class="error-message">请输入评分项名称</div>';
        html += '</div>';
        html += '<div class="col-sm-2">';
        html += '<input type="number" name="scoreItems[' + index + '].itemWeight" ' +
            'value="' + (item.itemWeight || 0) + '" class="form-control" min="1" placeholder="权重分值" required>';
        html += '<div class="error-message">权重分值必须大于0</div>';
        html += '</div>';
        html += '<div class="col-sm-1">';
        html += '<a class="btn-remove" onclick="removeItem(\'' + itemId + '\')"><i class="fa fa-times"></i></a>';
        html += '</div>';
        html += '</div>';
        html += '</div>';

        // 评分等级
        html += '<div class="form-group">';
        html += '<label class="col-sm-2 control-label">评分等级：</label>';
        html += '<div class="col-sm-10">';
        html += '<div id="levelsContainer_' + index + '">';

        // 生成评分等级，确保scoreLevels是数组
        var levels = item.scoreLevels || [];
        if (levels.length > 0) {
            for (var i = 0; i < levels.length; i++) {
                var level = levels[i] || {};
                html += generateLevelHtml(index, i, level);
            }
        } else {
            // 默认添加两个等级
            html += generateLevelHtml(index, 0);
            html += generateLevelHtml(index, 1);
        }

        html += '</div>';
        html += '<button type="button" class="btn btn-sm btn-success" ' +
            'onclick="addLevel(' + index + ')">';
        html += '<i class="fa fa-plus"></i> 添加评分等级';
        html += '</button>';
        html += '</div>';
        html += '</div>';
        html += '</div>';

        return html;
    }

    // 生成评分等级HTML，增强空值处理
    function generateLevelHtml(itemIndex, levelIndex, level) {
        // 确保level是对象，避免null引用错误
        level = level || {levelName: '', levelScore: 0, levelDesc: ''};
        var html = '<div class="level-item">';
        html += '<div class="form-group">';
        html += '<label class="col-sm-2 control-label">等级 ' + (levelIndex + 1) + '：</label>';
        html += '<div class="col-sm-3">';
        html += '<input type="text" name="scoreItems[' + itemIndex + '].scoreLevels[' + levelIndex + '].levelName" ' +
            'value="' + (level.levelName || '') + '" class="form-control" placeholder="等级名称(如：优秀)" required>';
        html += '<div class="error-message">请输入等级名称</div>';
        html += '</div>';
        html += '<div class="col-sm-2">';
        html += '<input type="number" name="scoreItems[' + itemIndex + '].scoreLevels[' + levelIndex + '].levelScore" ' +
            'value="' + (level.levelScore || 0) + '" class="form-control" min="0" placeholder="分值" required>';
        html += '<div class="error-message">分值必须大于等于0</div>';
        html += '</div>';
        html += '<div class="col-sm-4">';
        html += '<input type="text" name="scoreItems[' + itemIndex + '].scoreLevels[' + levelIndex + '].levelDesc" ' +
            'value="' + (level.levelDesc || '') + '" class="form-control" placeholder="等级描述" required>';
        html += '<div class="error-message">请输入等级描述</div>';
        html += '</div>';
        html += '<div class="col-sm-1">';
        html += '<a class="btn-remove" onclick="removeLevel(this)"><i class="fa fa-times"></i></a>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
        return html;
    }

    // 添加评分项
    function addItem() {
        var html = generateItemHtml(null, itemIndex);
        $("#scoreItemsContainer").append(html);
        itemIndex++;
    }

    // 移除评分项
    function removeItem(itemId) {
        if ($(".item-panel").length <= 1) {
            $.modal.alertWarning("至少保留一个评分项");
            return;
        }
        $("#" + itemId).remove();
        // 重新编号
        renumberItems();
    }

    // 添加评分等级
    function addLevel(itemIdx) {
        var container = $("#levelsContainer_" + itemIdx);
        var levelIndex = container.find(".level-item").length;
        var html = generateLevelHtml(itemIdx, levelIndex);
        container.append(html);
    }

    // 移除评分等级
    function removeLevel(element) {
        var levelItem = $(element).closest(".level-item");
        var container = levelItem.parent().parent().find(".level-item");

        if (container.length <= 1) {
            $.modal.alertWarning("至少保留一个评分等级");
            return;
        }

        levelItem.remove();

        // 重新编号
        var itemIdx = $(element).closest(".item-panel").attr("id").split("_")[1];
        renumberLevels(itemIdx);
    }

    // 重新编号评分项
    function renumberItems() {
        var items = $(".item-panel");
        items.each(function(index) {
            var oldId = $(this).attr("id");
            var newId = "item_" + index;
            $(this).attr("id", newId);

            // 更新评分项索引
            $(this).find("input[name^='scoreItems']").each(function() {
                var name = $(this).attr("name");
                var newName = name.replace(/scoreItems\[\d+\]/, "scoreItems[" + index + "]");
                $(this).attr("name", newName);
            });

            // 更新评分项标题
            $(this).find(".item-header label").text("评分项 " + (index + 1) + "：");

            // 更新等级容器ID
            var levelContainer = $(this).find("[id^='levelsContainer_']");
            var oldContainerId = levelContainer.attr("id");
            var newContainerId = "levelsContainer_" + index;
            levelContainer.attr("id", newContainerId);

            // 重新编号等级
            renumberLevels(index);
        });
    }

    // 重新编号评分等级
    function renumberLevels(itemIdx) {
        var container = $("#levelsContainer_" + itemIdx);
        var levels = container.find(".level-item");

        levels.each(function(levelIndex) {
            // 更新等级索引
            $(this).find("input[name^='scoreItems[" + itemIdx + "].scoreLevels']").each(function() {
                var name = $(this).attr("name");
                var newName = name.replace(/scoreLevels\[\d+\]/, "scoreLevels[" + levelIndex + "]");
                $(this).attr("name", newName);
            });

            // 更新等级标题
            $(this).find("label").text("等级 " + (levelIndex + 1) + "：");
        });
    }

    // 表单验证
    function validateForm() {
        var isValid = true;

        // 验证评分标准名称
        if (!$("#form-score-standard [name='standardName']").val()) {
            showError($("#form-score-standard [name='standardName']"), "请输入评分标准名称");
            isValid = false;
        } else {
            hideError($("#form-score-standard [name='standardName']"));
        }

        // 验证总分值
        var totalScore = parseInt($("#form-score-standard [name='totalScore']").val()) || 0;
        if (totalScore <= 0) {
            showError($("#form-score-standard [name='totalScore']"), "总分值必须大于0");
            isValid = false;
        } else {
            hideError($("#form-score-standard [name='totalScore']"));
        }

        // 验证所有评分项
        $(".item-panel").each(function(index) {
            var itemName = $(this).find("[name^='scoreItems[" + index + "].itemName']");
            if (!itemName.val()) {
                showError(itemName, "请输入评分项名称");
                isValid = false;
            } else {
                hideError(itemName);
            }

            var itemWeight = $(this).find("[name^='scoreItems[" + index + "].itemWeight']");
            var weightVal = parseInt(itemWeight.val()) || 0;
            if (weightVal <= 0) {
                showError(itemWeight, "权重分值必须大于0");
                isValid = false;
            } else {
                hideError(itemWeight);
            }

            // 验证所有评分等级
            $(this).find(".level-item").each(function(levelIndex) {
                var levelName = $(this).find("[name^='scoreItems[" + index + "].scoreLevels[" + levelIndex + "].levelName']");
                if (!levelName.val()) {
                    showError(levelName, "请输入等级名称");
                    isValid = false;
                } else {
                    hideError(levelName);
                }

                var levelScore = $(this).find("[name^='scoreItems[" + index + "].scoreLevels[" + levelIndex + "].levelScore']");
                var scoreVal = parseInt(levelScore.val()) || 0;
                if (scoreVal < 0) {
                    showError(levelScore, "分值必须大于等于0");
                    isValid = false;
                } else {
                    hideError(levelScore);
                }

                var levelDesc = $(this).find("[name^='scoreItems[" + index + "].scoreLevels[" + levelIndex + "].levelDesc']");
                if (!levelDesc.val()) {
                    showError(levelDesc, "请输入等级描述");
                    isValid = false;
                } else {
                    hideError(levelDesc);
                }
            });
        });

        return isValid;
    }

    // 显示错误信息
    function showError(element, message) {
        element.closest(".form-group").addClass("has-error");
        element.siblings(".error-message").text(message).show();
    }

    // 隐藏错误信息
    function hideError(element) {
        element.closest(".form-group").removeClass("has-error");
        element.siblings(".error-message").hide();
    }

    // 保存评分标准
    function saveScoreStandard() {
        if (!validateForm()) {
            return;
        }

        var data = $("#form-score-standard").serializeObject();

        // 验证总分和各项权重之和是否一致
        var totalScore = parseInt(data.totalScore) || 0;
        var items = data.scoreItems || [];
        var itemsTotal = 0;
        for (var i = 0; i < items.length; i++) {
            itemsTotal += parseInt(items[i].itemWeight) || 0;
        }

        if (totalScore !== itemsTotal) {
            $.modal.alertWarning("各项权重分值之和必须等于总分值");
            return;
        }

        // 为每个评分项添加验证：等级分值总和应等于权重分值
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            var itemWeight = parseInt(item.itemWeight) || 0;
            var levels = item.scoreLevels || [];
            var levelsTotal = 0;

            for (var j = 0; j < levels.length; j++) {
                levelsTotal += parseInt(levels[j].levelScore) || 0;
            }

            if (itemWeight !== levelsTotal) {
                $.modal.alertWarning("评分项 " + (i + 1) + " 的等级分值总和必须等于其权重分值");
                return;
            }
        }

        $.ajax({
            url: prefix + "/save",
            type: "post",
            data: JSON.stringify(data),
            contentType: "application/json;charset=utf-8",
            success: function(data) {
                if (data.code === 0) {
                    $.modal.alertSuccess("保存成功", function() {
                        window.location.href = prefix + "/scoreStandard";
                    });
                } else {
                    $.modal.alertError(data.msg);
                }
            },
            error: function() {
                $.modal.alertError("保存失败，请稍后重试");
            }
        });
    }

    $(function() {
        // 初始化评分项，增强空值处理
        if (scoreStandard && scoreStandard.scoreItems && Array.isArray(scoreStandard.scoreItems) && scoreStandard.scoreItems.length > 0) {
            for (var i = 0; i < scoreStandard.scoreItems.length; i++) {
                var itemHtml = generateItemHtml(scoreStandard.scoreItems[i], i);
                $("#scoreItemsContainer").append(itemHtml);
            }
        } else {
            // 默认添加一个评分项
            addItem();
        }

        // 添加评分项按钮点击事件
        $("#addItemBtn").click(addItem);

        // 保存按钮点击事件
        $("#submitBtn").click(saveScoreStandard);

        // 为所有输入框添加实时验证
        $("input, textarea").on("blur", function() {
            validateForm();
        });
    });
</script>
</body>
</html>